﻿using System;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;

public class TcpConnect : MonoBehaviour
{

    public string m_sIp;
    public int m_iPoint;
    public byte[] m_bData = new byte[1024];

    static public TcpConnect g_Instance;

    //SocketAsyncEventArgs m_ConnectEventArg = new SocketAsyncEventArgs();

    Socket m_sClientSocket;


    // Use this for initialization
    void Start() {
        m_sClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        if (m_sClientSocket == null)
        {
            Debug.Assert(m_sClientSocket == null, "init socket fail , socket is null");
            return;
        }

        m_sClientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 0);
        m_sClientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 1000);

        g_Instance = this;
        //m_ConnectEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(SocketIsReady);

        //bool willRaiseEvent = m_sClientSocket.ConnectAsync(m_ConnectEventArg);
        //if (!willRaiseEvent)
        //{
        //    ProcConnected(m_ConnectEventArg);
        //}
    }

    // Update is called once per frame
    void Update() {
        bool bConnected = m_sClientSocket.Connected;

        if (bConnected == false)
        {
            try
            {
                //m_sClientSocket.Connect(m_sIp, m_iPoint);
            }
            catch (SocketException e)
            {

            }
        }

        if (m_sClientSocket.Connected)
        {
            if (bConnected == false)
            {
                Debug.Log("connect server.ip:" + m_sIp + ",point:" + m_iPoint);
                m_sClientSocket.BeginReceive(m_bData, 0, 1024, SocketFlags.None, new AsyncCallback(RecieveMassageCallback), null);

                Debug.Log("begin to recieve data");
            }


            //int iReceiveNumber = m_sClientSocket.Receive(m_bData, SocketFlags.None);

            //if(iReceiveNumber == 0)
            {
                //    m_sClientSocket.Disconnect(true);
            }

            //Debug.Log("recieve data from server.data:" + m_bData.ToString());
        }
        else
        {
            if (bConnected == true)
            {
                Debug.Log("disconnect server.ip:" + m_sIp + ",point:" + m_iPoint);
            }
        }

    }

    void RecieveMassageCallback(IAsyncResult cResult)
    {
        int iRead = m_sClientSocket.EndReceive(cResult);

        if (iRead > 0)
        {
            Debug.Log("recieve server data. data:" + Encoding.Default.GetString(m_bData, 0, iRead) + ", len:" + m_bData.Length);
            
            
            m_sClientSocket.BeginReceive(m_bData, 0, 1024, SocketFlags.None, new AsyncCallback(RecieveMassageCallback), null);
        }
        else
        {
            m_sClientSocket.Disconnect(true);
        }
    }

    public int SendMessageToServer( string sMessage )
    {
        int iSendLength = 0;
        if( m_sClientSocket.Connected )
        {
            iSendLength = m_sClientSocket.Send(Encoding.UTF8.GetBytes(sMessage) );
        }
        else
        {
            Debug.Log("not connect server, wait connneted before send message");
        }
        Debug.Log("send massage to server.message:"+sMessage);

        return iSendLength;
    }
    //void SocketIsReady(object sender, SocketAsyncEventArgs cEvent)
    //{
    //    switch(cEvent.LastOperation)
    //    {
    //        case SocketAsyncOperation.Connect:
    //            ProcConnected(cEvent);
    //            break;
    //        case SocketAsyncOperation.Receive:
    //            break;
    //        case SocketAsyncOperation.Send:
    //            break;
    //        default:
    //            throw new ArgumentException("The last operation completed on the socket was not a connect or receive or send. operation:"+cEvent.LastOperation);
    //    }
    //}

    //void ProcConnected(SocketAsyncEventArgs cEvent)
    //{
    //    Debug.Log("connected. ip:" + m_sIp + ", point:" + m_iPoint);
    //}
}
